package com.yaorange.jk.service.impl;

import com.yaorange.jk.dao.BaseDao;
import com.yaorange.jk.entity.Contract;
import com.yaorange.jk.service.ContractService;
import com.yaorange.jk.utils.Pagination;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;

/**
 * @author coach tam
 * @date 2017/11/1
 */
@Service("contractService")
@Transactional
public class ContractServiceImpl implements ContractService {

    private Logger logger = Logger.getLogger(ContractServiceImpl.class);

    @Autowired
    private BaseDao<Contract,String> contractDao;



    @Override
    @Transactional(readOnly = true)
    public Pagination findPage(int pageNo, int pageSize, int state) {
        String hql = "from Contract u where 1=1 and state=?";
        return contractDao.pageByHql(hql,pageNo,pageSize,state);
    }


    @Override
    public List<Contract> findAll() {
        return contractDao.getListByHQL("from Contract");
    }

    @Override
    public void save(Contract contract) {
        contract.setTotalAmount(0d);
        contract.setState(0);
        contractDao.save(contract);
    }

    @Override
    public Contract findById(String id) {
        return contractDao.get(Contract.class,id);
    }

    @Override
    public void update(Contract model) {
        //通过id查询到数据库数据
        Contract contract = contractDao.get(Contract.class,model.getId());
//        contractDao.evcit(contract);
        model.setCreateTime(contract.getCreateTime());
        model.setUpdateTime(new Timestamp(System.currentTimeMillis()));

        model.setTotalAmount(contract.getTotalAmount());
        model.setState(contract.getState());
        contractDao.merge(model);
    }

    @Override
    public void deleteByIds(String[] ids) {
        for (String id :ids)
        {
            contractDao.deleteById(Contract.class,id);
        }
    }

    @Override
    public List<Contract> findByDeliveryPeriod(String now) {
        return  contractDao.getListByHQL("from Contract c where to_char(c.deliveryPeriod,'yyyy-mm-dd')=?",now);
    }

    @Override
    public void submitByIds(String[] ids) {
        for (String id :ids)
        {
//            String hql = "update Contract set state = 1 where id in (ids)";
            Contract contract = contractDao.get(Contract.class,id);
            contract.setState(1);
            contractDao.update(contract);
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Contract findByContractname(String contractname) {
        return contractDao.getByHQL("from Contract where contractName=?",contractname);
    }


}
